package com.ucar.train.service.wufuqiang;

import org.springframework.stereotype.Component;

import java.util.concurrent.*;

/**
 * @author wufuqiang
 * @title: Tire
 * @projectName:wufuqiang_thread
 * @description: T0D0
 * @created 2019-08-21 17:11
 */
@Component("tire")
public class Tire extends Handle{

    @Override
    public void process(Car car) {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        FutureTask<String> future =
                new FutureTask<String>(new Callable<String>() {//使用Callable接口作为构造参数
                    public String call() throws Exception, TimeoutException {
                        System.out.println("进入轮胎保养流程");
                        System.out.println(car.toString());
                        //未加机油
                        if (!car.isTire()) {
                            int a = (int) (1 + Math.random() * 10);
                            //成功
                            if (a <= 8) {
                                car.setTire(true);
                                System.out.println("轮胎保养成功");
                            } else { //失败
                                System.out.println("轮胎保养失败");
                                throw new Exception();
                            }
                        }
                        return null;
                    }
                });
        executor.execute(future);
        try {
            String result = future.get(1000, TimeUnit.MILLISECONDS); //取得结果，同时设置超时执行时间为5秒。同样可以用future.get()，不设置执行超时时间取得结果
            if (getNextHandle() != null){
                getNextHandle().process(car);
            }else {
                System.out.println("保养完成");
            }
        } catch (TimeoutException e) {
            System.out.println("轮胎执行超时,重新执行");
            process(car);
        } catch (Exception e) {
            process(car);
        }finally {
            executor.shutdownNow();
        }
    }
}
